<!-- 下单页 -->
<template>
	<view class="confirm-order-page flex-column">
		<!-- isSuccess：{{ isSuccess }} -->
		<!-- addressItem==={{ addressItem }}==id:{{ addressItem.id }}==consignee:{{ addressItem.consignee }} -->
		<view class="card-cls address-all flex-align-center" @click="selectAddress">
			<block v-if="addressItem && addressItem.id">
				<view class="icon-bj flex"><text class="iconfont icon-dingweiweizhi"></text></view>
				<view class="flex-columns flex1">
					<view class="address-content">
						<text class="font-overflow p-right10 font32" style="max-width: 200rpx;">{{ addressItem.consignee }}</text>
						{{ addressItem.mobile }}
					</view>
					<view class="address-content p-top10 color666 font26 font-overflow2">{{ addressItem.address }} {{ addressItem.detailsAddress }}</view>
				</view>
				<image src="/static/right-arrow.png"></image>
			</block>
			<block v-else>
				<view class="icon-bj flex"><text class="iconfont icon-dingweiweizhi"></text></view>
				<view class="address-content">请选择地址</view>
				<image src="/static/right-arrow.png"></image>
			</block>
		</view>
		<view class="card-cls p-align40">
			<view class="flex-between border p-bottom30">
				<view class="font32">服务时间</view>
				<view class="color999" @click="timeOpen">{{ serviceStartTime || service_message }}</view>
			</view>
			<view class="flex-between p-top20">
				<view class="font32">出行方式</view>
				<view class="flex-align-center">
					<radio-group name="apply">
						<label><radio class="min-radio" value="1" color="#19C866" checked /></label>
					</radio-group>
					出租车
				</view>
			</view>
		</view>
		<view class="card-cls flex-align-center">
			<image class="project-img" :src="projectInfo.rotationChart"></image>
			<view class="flex-auto-columns flex1 height81">
				<view class="flex-columns">
					<view class="font32 p-bottom10">{{ projectInfo.tradeName }}</view>
					<view class="color999 font24">服务理疗师：{{ technicianInfo.technicianName }}</view>
				</view>
				<view class="flex-between">
					<view class="flex-align-center">
						<text class="red font32">￥{{ projectInfo.servicePrice }}</text>
						<view class="color999 font24">/ {{ projectInfo.serviceTime }}分钟</view>
					</view>
					<view class="color999 font24">数量：x1</view>
				</view>
			</view>
		</view>
		<view class="card-cls">
			<view class="flex-between border p-bottom30">
				<view class="font32">卡券优惠</view>
				<!-- 判断0则取领券，否则使用优惠券 -->
				<view class="color999 flex-align-center" @click="couponOpen" v-if="couponDeduction && couponDeduction.id">
					<!-- 新人/折扣，券的区分标识 -->
					<view class="red p-right10">
						<view class="coupon-cls color_FFFFFF m-right10">{{ couponDeduction.discountCouponType == 1 ? '满减' : '新用户' }}</view>
						-￥{{ couponDeduction.cardRollAmount }}
					</view>
					>
				</view>
				<view class="color999" @click="couponOpen" v-else>{{ list.length || 0 }}张可用 ></view>
			</view>
			<view class="flex-between p-top20 border p-bottom30" v-if="deductionAmount > 0">
				<view class="font32">{{ integralName }}抵扣</view>
				<view class="red flex-align-center">
					￥{{ deductionAmount || 0 }}
					<radio-group name="apply">
						<label class="m-left10"><radio class="min-radio" :checked="checked" value="1" color="#ff0000" @click="checkedOn()" /></label>
					</radio-group>
				</view>
			</view>
			<view class="p-bottom30" :class="{ border: !details }">
				<view class="flex-between p-top20">
					<view class="font32">预估出行费</view>
					<view class="red">￥{{ fareInfo.fare || 0 }}</view>
				</view>
				<view class="color999 font24 p-top30">{{ details }}</view>
			</view>
			<view class="p-notes">
				<view class="font32">
					订单备注
					<text class="color999 font24">（选填）</text>
				</view>
				<view class="textarea-box">
					<textarea placeholder-style="font-size:30rpx;" v-model="orderNotes" placeholder="输入订单备注" maxlength="50" @input="descInput" style="height: 200rpx;" />
					<view class="textarea-color">{{ remnant }}/50</view>
				</view>
			</view>
		</view>
		<!-- 余额/微信支付 -->
		<view class="card-cls">
			<radio-group name="apply" @change="handleApplyType">
				<view class="flex-between p-align-top20">
					<view class="flex-align-center">
						<!-- <image class="zfimg-cls" src="/static/zfwx.png"></image> -->
						<view>微信支付</view>
					</view>
					<label class="m-left10"><radio class="min-radio" value="2" color="#19C866" checked /></label>
				</view>
				<view class="flex-between p-align-top20">
					<view class="flex-align-center">
						<!-- <image class="zfimg-cls" src="/static/zfye.png"></image> -->
						<view>余额支付（可用：￥{{ balanceMoney || '0.00' }})</view>
					</view>
					<label class="m-left10">
						<radio
							class="min-radio"
							value="1"
							color="#19C866"
							:class="balanceMoney <= 0 || Number(balanceMoney) < Number(sum) ? 'radio-disabled' : ''"
							:disabled="balanceMoney <= 0 || Number(balanceMoney) < Number(sum) ? true : false"
						/>
					</label>
				</view>
			</radio-group>
		</view>

		<view class="flex-between confirm-bottom">
			<view class="flex-columns">
				<view class="flex-align-center sum-price flex1">
					<view>合计：</view>
					<text>￥{{ sum }}</text>
				</view>

				<view class="color999 font24" v-if="couponDeduction && couponDeduction.id">
					<!-- 新人/折扣，券的区分标识 -->
					已选择{{ couponDeduction.discountCouponType == 1 ? '满减' : '新用户' }}券-￥{{ couponDeduction.cardRollAmount }}
				</view>
				<view class="color999 font24" v-else>暂无选择优惠券</view>
			</view>
			<button @click="confirm">提交订单</button>
		</view>
		<!-- 可使用“优惠券” 弹出框 -->
		<sunui-popup ref="pop">
			<template v-slot:content>
				<view class="v-coupon-pop">
					<view class="font32 p-bottom30 text-align">请选择优惠券</view>
					<!-- <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"> -->
					<block v-if="list.length > 0">
						<scroll-view :scroll-y="true" style="height: 600rpx;">
							<radio-group name="apply">
								<block v-for="(i, j) in list" :key="j">
									<view class="coupon-card">
										<!-- discountCouponType：优惠劵类型 （1.满检 3.新用户） -->
										<view class="identifying coupon-cls">{{ i.cardRoll.discountCouponType == 1 ? '满减神券' : '新用户专享' }}</view>
										<view class="flex-align-center padding20">
											<view class="flex-align-center coupon-price">
												<text>{{ i.cardRoll.cardRollAmount }}</text>
												元
											</view>
											<view class="flex-between flex1">
												<view>
													<view class="color333">{{ i.cardRoll.cardRollName }}</view>
													<view class="v-time">有效期：{{ i.cardRoll.periodValidityEnd ? i.cardRoll.periodValidityEnd.split('T')[0] : '' }}</view>
													<view class="v-discount">满{{ i.cardRoll.howMuchAvailable }}减去{{ i.cardRoll.cardRollAmount }}</view>
												</view>
												<label class="m-left10" @click="couponCheck(i)">
													<radio class="min-radio" value="1" color="#F28331" :checked="couponDeduction.id == i.cardRoll.id ? true : false" />
												</label>
											</view>
										</view>
										<view class="coupon-hint">{{ i.cardRoll.couponDescription }}</view>
									</view>
								</block>
							</radio-group>
						</scroll-view>
						<view class="confirm-time flex" @click="couponConfirm">确定</view>
					</block>
					<block v-else>
						<view class="empty-cls flex-column">
							<image src="/static/nodata.png"></image>
							<text class="text underline" @click="toGetCoupon">暂无优惠券，去领券大厅看看~</text>
						</view>
					</block>
					<!-- </mescroll-body> -->
				</view>
			</template>
		</sunui-popup>

		<!-- “服务时间” 弹出框 -->
		<sunui-popup ref="timepop">
			<template v-slot:content>
				<view class="v-time-pop">
					<view class="p-bottom30">
						<sunui-navbar
							:items="dayList"
							lineHeight="70rpx"
							:isCenter="true"
							:currentIndex="daytIndex"
							:size="180"
							color="#666"
							activeLineBg="#25c376"
							textAlign="center"
							activeColor="#25c376"
							activeLineWidth="30%"
							activeDirection="center"
							activeLineHeight="6rpx"
							bgColor="#fff"
							:margin="10"
							@change="getChange"
						></sunui-navbar>
					</view>
					<scroll-view :scroll-y="true" style="height: 600rpx;">
						<view class="flex-wrap">
							<block v-for="(i, j) in timeList" :key="j">
								<view
									class="flex-column time-cls"
									:class="timeIndex == j ? 'sel-time-cls' : i.isDisable == true ? 'none-time-cls' : 'v-time-pop'"
									@click="timeClick(j)"
								>
									<text>{{ i.time.split(' ')[1] }}</text>
									<view class="p-top10">{{ i.isDisable == true ? '不可预约' : '可预约' }}</view>
								</view>
							</block>
						</view>
					</scroll-view>
					<view class="confirm-time flex" @click="timeConfirm">确定</view>
				</view>
			</template>
		</sunui-popup>

		<!-- 协议弹框 -->
		<!-- <sunui-popup ref="agreementPop">
			<template v-slot:content>
				<view class="flex-columns v-agree-pop">
					<view class="v-title">请认真阅读确认</view>
					<view class="agree-name" @click="toAgreement">《隐私协议》</view>
					<view class="agree-confirm flex" @click="agreeClick">同意</view>
					<view class="agree-cancle flex" @click="agreeClose">不同意，再看看</view>
				</view>
			</template>
		</sunui-popup>
 -->
		<!-- 隐私协议 -->
		<radio-group name="apply" class="radioText flex-align-center" :class="'animation-' + animation" @click="checkedOn2()">
			<label @click.stop="checkedOn2()"><radio :checked="agreeChecked" value="1" color="#19c866" style="transform:scale(0.8);padding-left:12rpx;" /></label>
			<view class="agree flex-align-center">
				<view>我已阅读并同意</view>
				<text @click.stop="toAgreement()">《平台交易规则》</text>
			</view>
		</radio-group>
	</view>
</template>

<script>
import common from '@/common/js/common.js';
export default {
	data() {
		return {
			integralName: uni.getStorageSync('integralName') ? uni.getStorageSync('integralName') : '积分',
			isSuccess: false, //判断下单是否进入成功，进入成功，则为true，不能在进入complete
			balanceMoney: 0, //我的余额
			daytIndex: 0, //自定义索引
			dayList: common.weekDate().dayList, // "服务时间"后一周时间list
			// 忙时设置
			busySetList: [],
			timeIndex: -1, //“服务时间”点击index
			timeList: [
				{ time: '00:30', isDisable: false },
				{ time: '01:00', isDisable: false },
				{ time: '01:30', isDisable: false },

				{ time: '02:00', isDisable: false },
				{ time: '02:30', isDisable: false },
				{ time: '03:00', isDisable: false },
				{ time: '03:30', isDisable: false },

				{ time: '04:00', isDisable: false },
				{ time: '04:30', isDisable: false },
				{ time: '05:00', isDisable: false },
				{ time: '05:30', isDisable: false },

				{ time: '06:00', isDisable: false },
				{ time: '06:30', isDisable: false },
				{ time: '07:00', isDisable: false },
				{ time: '07:30', isDisable: false },

				// old start
				{ time: '08:00', isDisable: false },
				{ time: '08:30', isDisable: false },
				{ time: '09:00', isDisable: false },
				{ time: '09:30', isDisable: false },

				{ time: '10:00', isDisable: false },
				{ time: '10:30', isDisable: false },
				{ time: '11:00', isDisable: false },
				{ time: '11:30', isDisable: false },

				{ time: '12:00', isDisable: false },
				{ time: '12:30', isDisable: false },

				{ time: '13:00', isDisable: false },
				{ time: '13:30', isDisable: false },

				{ time: '14:00', isDisable: false },
				{ time: '14:30', isDisable: false },

				{ time: '15:00', isDisable: false },
				{ time: '15:30', isDisable: false },

				{ time: '16:00', isDisable: false },
				{ time: '16:30', isDisable: false },

				{ time: '17:00', isDisable: false },
				{ time: '17:30', isDisable: false },

				{ time: '18:00', isDisable: false },
				{ time: '18:30', isDisable: false },

				{ time: '19:00', isDisable: false },
				{ time: '19:30', isDisable: false },

				{ time: '20:00', isDisable: false },
				{ time: '20:30', isDisable: false },

				{ time: '21:00', isDisable: false },
				{ time: '21:30', isDisable: false },

				{ time: '22:00', isDisable: false },
				{ time: '22:30', isDisable: false },
				// old end
				{ time: '23:00', isDisable: false },
				{ time: '23:30', isDisable: false },

				{ time: '24:00', isDisable: false }
			],
			list: [], //卡券list
			// projectList: [], //项目list
			projectInfo: {}, //项目内容
			technicianInfo: {}, //理疗师信息
			details: '',
			details2: '直线距离2.07km，不是导航距离!每个订单都需要付给理疗师往返路费，打车费由高德地图估算。起步7元。超过2公里但不足13公里每公里增加1.9元',
			// 在picker列表所选中项的befor_school
			service_time: '',
			// 在picker列表所选中项的id
			sid: '',
			serviceAll: [],
			service_message: '请选择预约时间 >',
			remnant: 0,
			selServiceStartTime: '', //选中的，服务开始时间
			serviceStartTime: '', //服务开始时间
			fareInfo: {}, //出行费用
			orderNotes: '', //订单备注
			checked: false, //积分抵扣单选框
			pointsUsed: 0, //可抵扣积分
			deductionAmount: 0, //可抵扣金额（积分)
			allDeductionMoney: 0, //抵扣金额（总）
			couponDeduction: {}, //卡券抵扣item
			couponItem: {}, // 选中的卡券item
			applyType: 2, // 支付方式：1 余额支付  2 微信支付
			addressItem: {}, // 获取默认地址内容
			// addressItem: uni.getStorageSync('addressItem') || '' //选中的地址内容
			agreeChecked: false, //隐私协议 单选框
			animation: '' // 动画样式
		};
	},
	computed: {
		// 在优惠券的前提下，在总计为负数的前提下。积分可以部分抵扣
		sum() {
			// this.checked=true 代表积分抵扣勾选
			let deductionAmount = this.deductionAmount || 0; // 积分抵扣金额
			deductionAmount = this.checked == true ? deductionAmount : 0;
			let fare = this.fareInfo.fare || 0; // 出行费
			let couponMoney = this.couponDeduction.id ? this.couponDeduction.cardRollAmount : 0; // 卡券优惠金额
			let sum = 0;
			// he=实付款+出行费
			let he = Number(this.projectInfo.servicePrice) + Number(fare);
			// jian=积分抵扣+优惠券
			let jian = Number(deductionAmount) + Number(couponMoney);
			this.allDeductionMoney = Number(jian); //抵扣金额（总）
			console.log('he,jian', he, jian, 'deductionAmount', deductionAmount);
			// sum计算，如果付款金额减去扣除金额<0,则直接为0.并且计算积分的扣除
			sum = Number(he - jian) > 0 ? he - jian : '0.01';
			return Number(sum).toFixed(2);
		}
	},
	onLoad(options) {
		console.log('options========', options, 'getNowDate()', this.$sun.getNowDate());
		// this.$sun.unparam():将url字符串解析成对象
		this.projectInfo = this.$sun.unparam(decodeURIComponent(options.projectInfo)); //项目对象
		this.technicianInfo = this.$sun.unparam(decodeURIComponent(options.technicianInfo)); // 理疗师对象

		this.getUserInfo(); //获取我的余额
		this.queryCoupons(); // 查询用户可用优惠卷
		this.queryIntegrals(); // 查询用户可抵扣积分
		this.getBySelectBusyHourSettings(); //查询忙时设置 数据回显

		// this.dayList = common.weekDate().dayList;
		/* console.log('this.dayList', this.dayList);
				var pages = getCurrentPages(); //当前页
				var beforePage = pages[pages.length - 2]; //上个页面
				this.projectList = beforePage.$vm.projectList;
				this.projectInfo = this.projectList[0];
				console.log('projectList,beforePage', this.projectList, beforePage); */
		// this.pid = beforePage.$vm.pid2 ? beforePage.$vm.pid2 : '';
		// 积分能抵扣的钱
		/* if (this.integral > this.ratio) {
					this.integralMoney = Number(this.integral / this.ratio).toFixed(2);
					this.integralBack = Number(this.integral / this.ratio).toFixed(2);
				} */
	},
	onShow() {
		console.log('进入onshow=======', this.addressItem);
		this.$at.releaseKey('submit');
		this.queryAddress(); //获取默认地址
		// this.updateDiscountCoupons();
	},
	methods: {
		// 去查看隐私协议
		toAgreement() {
			this.$sun.navGo('/pages/user/my/service-declaration/service-declaration?type=2');
		},
		//单选 选择框
		checkedOn2() {
			// 将this.agreeChecked==true 做条件判断，且赋值给agreeChecked。
			this.agreeChecked = this.agreeChecked == true ? false : true;
		},
		// 查询忙时设置 数据回显（公众号使用）
		async getBySelectBusyHourSettings() {
			const result = await this.$http.get({
				url: this.$api.getBySelectBusyHourSetting,
				data: {
					technicianId: Number(this.technicianInfo.id)
				}
			});
			if (result.code == 200) {
				console.log('查询忙时设置 数据回显result.', result);
				this.busySetList = result.data;
				this.getTechnicianHourSettings();
			} else {
				this.$sun.toast(result.message);
			}
		},
		// 查询技师已预约时间 数据回显（公众号使用）
		async getTechnicianHourSettings() {
			const result = await this.$http.get({
				url: this.$api.getTechnicianHourSetting,
				data: {
					technicianId: Number(this.technicianInfo.id)
				}
			});
			if (result.code == 200) {
				console.log('查询技师已预约时间 数据回显result.', result.data);
				let addList = result.data;
				for (let i = 0; i < addList.length; i++) {
					console.log('addList[i].service_time11', addList[i].service_time);
					let time = addList[i].service_time;
					let date = time.split(' ')[0];
					let hourAll = time.split(' ')[1];
					let hour = hourAll.split(':')[0];
					let min = hourAll.split(':')[1];
					let mis = hourAll.split(':')[2];
					console.log('hour,min,mis', hour, min, mis);
					if (min > '30' && min != '30') {
						min = '30';
					}
					if (min < '30' && min != '00') {
						min = '00';
					}
					let hourAll2 = hour + ':' + min + ':' + mis;

					console.log('hour', hour);
					addList[i].service_time = date + 'T' + hourAll2;
					console.log('addList[i].service_time222', addList[i].service_time);
				}
				this.busySetList = this.busySetList.concat(addList);
				this.getChange(0);
				console.log('查询技师已预约时间 this.busySetList', this.busySetList);
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 获取头部用户信息
		async getUserInfo() {
			const result = await this.$http.get({
				url: this.$api.getPersonInfo,
				data: {
					// siteId: uni.getStorageSync('siteId'), // 站点id
					userId: uni.getStorageSync('userId') //登录用户的id
				}
			});
			if (result.code == 200) {
				console.log('获取头部用户信息result.', result);
				this.balanceMoney = Number(result.data.balance).toFixed(2); //我的余额
			} else {
				this.$sun.toast(result.message);
			}
		},
		// 获取tabList数据
		getChange(index) {
			console.log('index', index);
			this.timeList.map(item => {
				item.isDisable = false;
				console.log('item', item);
				// return{}
			});
			this.daytIndex = index;
			console.log('this.dayList[this.daytIndex]', this.dayList[this.daytIndex], this.dayList[this.daytIndex].date);

			/* 做timeList，中的time，年月日时分秒赋值 。start */
			for (let i = 0; i < this.timeList.length; i++) {
				// console.log('this.timeList[i].time', this.timeList[i].time);
				// console.log('i', this.timeList[i]);
				// 第一次进入，则不需要做分割,并且找不到为空格间隔的
				// 日期字符串中不包含空格，则没有年月日
				if (index == 0 && this.timeList[i].time.indexOf(' ') == -1) {
					this.timeList[i].time = this.dayList[this.daytIndex].date + ' ' + this.timeList[i].time;
				} else {
					this.timeList[i].time = this.dayList[this.daytIndex].date + ' ' + this.timeList[i].time.split(' ')[1];
				}
			}
			console.log('aaaaaaaaaathis.timeList', this.timeList);
			/* 做timeList，中的time，年月日时分秒赋值 。end */

			/* 做timelist,如果当天日期超出，则不能被选中 start */
			// index==0 代表当天
			let nextIndex = 0;
			for (let i = 0; i < this.timeList.length; i++) {
				if (index == 0) {
					let oldTime = this.timeList[i].time + ':00';
					if (oldTime < this.$sun.getNowDate()) {
						this.$set(this.timeList[i], 'isDisable', true);
						nextIndex = i;
					}
				}
			}
			// 统一多加半小时预约时间（因此条件判断不需要=）
			this.$set(this.timeList[nextIndex + 1], 'isDisable', true);
			/* end */

			/* 做忙时设置判断，如果时间相同，则将isDisable（禁用）设置为true ——start */
			for (let j = 0; j < this.busySetList.length; j++) {
				for (let i = 0; i < this.timeList.length; i++) {
					let serviceTime = this.busySetList[j].service_time.split('T')[0] + ' ' + this.busySetList[j].service_time.split('T')[1];
					// console.log('serviceTime',serviceTime,'this.timeList[i].time',this.timeList[i].time );
					if (serviceTime == this.timeList[i].time + ':00') {
						console.log('进入改变isDisable===========');
						this.$set(this.timeList[i], 'isDisable', true);
					}
				}
			}
			/* 做忙时设置判断，如果时间相同，则将isDisable（禁用）设置为true ——end */

			console.log('22222222222this.timeList[i]', this.timeList);
			//清空预约时间time start
			this.timeIndex = -1;
			this.selServiceStartTime = '';
			//清空预约时间time end
		},
		// “服务时间”点击事件
		timeClick(index) {
			// this.selServiceStartTime = '';
			let time = '';
			console.log('this.timeList[this.timeIndex]', this.timeList[this.timeIndex], 'this.timeList', this.timeList);
			// 可预约状态，才能进入
			if (this.timeList[index].isDisable == false) {
				this.timeIndex = index;
				// let day = this.dayList[this.daytIndex].date;
				// this.serviceStartTime = day + ' ' + time;
				time = this.timeList[this.timeIndex].time;
				this.selServiceStartTime = time;
				console.log('服务时间,this.timeList', this.timeList, 'this.selServiceStartTime', this.selServiceStartTime);
			}
		},
		// 确定，选中的 “服务时间”点击事件
		timeConfirm() {
			if (!this.selServiceStartTime) {
				this.$sun.toast('请选择预约时间');
				return;
			}
			/* 预约时间和服务时间算的不足判断，需要测试 */
			/* const dateObj = new Date(this.selServiceStartTime);
			// console.log("dateObj===",dateObj);
			// 2、在当前时间dateObj变量上加上【服务时长】分钟
			var addMinute = new Date(dateObj.setMinutes(dateObj.getMinutes() + Number(this.projectInfo.serviceTime))); //addMinute: Fri May 22 2020 19:21:37 GMT+0800 (中国标准时间)
			// console.log('addMinute:', addMinute,'this.$sun.newDate',this.$sun.newDate(addMinute))
			// console.log("this.selServiceStartTime",this.selServiceStartTime)

			// this.selServiceStartTime 当前预约时间
			// this.$sun.newDate(addMinute) 计算的当前预约结束时间
			// 去筛选 禁用时间,有没有大于当前预约时间 && 小于等于 计算的当前预约结束时间,如果有,代表后面的时间被预定了,用户不能选择
			// console.log('this.busySetList',this.busySetList)

			var flag = false; // 初始化标志变量为false
			for (let i = 0; i < this.busySetList.length && !flag; i++) {
				let startTime = this.selServiceStartTime + ':00';
				let endTime = this.$sun.newDate(addMinute);
				let nowTime = this.$sun.dateConversion(this.busySetList[i].service_time);
				if (nowTime > startTime && nowTime <= endTime) {
					console.log('找到了目标元素');
					flag = true; // 当满足条件时将标志变量设置为true，从而提前结束循环
					console.log('已达到要求时间nowTime,startTime,endTime', nowTime, startTime, endTime);
				}
			}
			console.log('退出循环',flag,flag==true);
			if (flag==true) {
				console.log("12333333333")
				this.$sun.toast('预约时间不足,请重选时间');
				return;
			} */

			this.serviceStartTime = '';
			this.serviceStartTime = this.selServiceStartTime;
			this.closeTime();
		},

		// 打开“协议”弹框，同意后即可进入下单
		agreeOpen() {
			this.$refs.agreementPop.show({
				anim: 'center',
				shadeClose: false,
				topclose: false
			});
		},
		agreeClose() {
			this.$refs.agreementPop.close();
		},
		// 打开“服务时间”弹窗
		timeOpen() {
			this.$refs.timepop.show({
				anim: 'bottom',
				position: 'bottom',
				shadeClose: true, //false使用户不能点击其它关闭页面
				topclose: false
			});
		},
		// 关闭“服务时间”弹窗
		closeTime() {
			this.$refs.timepop.close();
		},
		// 打开“卡券”弹框
		couponOpen() {
			console.log('this.list', this.list, this.list.length);
			if (this.list && this.list.length > 0) {
				this.$refs.pop.show({
					anim: 'bottom',
					position: 'bottom',
					shadeClose: true, //false使用户不能点击其它关闭页面
					topclose: false
				});
			}
		},
		// 关闭“卡券”弹框
		closeCopupon() {
			this.$refs.pop.close();
		},
		// 优惠券单选，点击事件
		couponCheck(i) {
			this.couponItem = i;
			console.log('i', i);
			i.checked = true;
			// i.checked = i.checked == true ? false : true;
			// this.couponDeduction = i.checked == false ? {} : i.cardRoll; //卡券抵扣item
			// this.couponDeduction = {};
			// this.couponDeduction = i.cardRoll; //卡券抵扣item
		},
		// 确认优惠券
		couponConfirm() {
			this.couponDeduction = {};
			this.couponDeduction = this.couponItem.cardRoll; //卡券抵扣item
			this.closeCopupon();
		},
		// 去领券大厅
		toGetCoupon() {
			this.$sun.navGo('/pages/user/my/voucherHall/voucherHall');
			this.closeCopupon();
		},

		// 单选框
		handleApplyType(e) {
			let val = e.detail.value;
			this.applyType = val;
			console.log('this.applyType', this.applyType);
		},
		// 积分抵扣单选框
		handleApplyType2(e) {
			let val = e.detail.value;
		},
		//积分抵扣：单选 选择框
		checkedOn() {
			// 积分抵扣，需要做sum加减
			this.checked = this.checked == true ? false : true;
		},

		// 获取默认地址
		async queryAddress() {
			const result = await this.$http.get({
				url: this.$api.getDefaultAddress,
				data: {
					userId: uni.getStorageSync('userId') //登录用户的id
				}
			});
			if (result.code == 200) {
				this.addressItem = result.data;
				console.log('获取默认地址result', result, 'this.addressItem', this.addressItem);
				if (this.addressItem && this.addressItem.latitude) {
					this.getFare(); // 查询预估车费
				} else {
					this.fareInfo = '';
					this.details = '';
				}
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 查询用户可用优惠卷
		async queryCoupons() {
			const result = await this.$http.get({
				url: this.$api.querySelectCoupon,
				data: {
					money: this.projectInfo.servicePrice,
					// money: 500,
					siteId: uni.getStorageSync('siteId'), // 站点id
					userId: uni.getStorageSync('userId') //登录用户的id
				}
			});
			if (result.code == 200) {
				console.log('查询用户可用优惠卷result', result);
				this.list = result.data || [];
				if (this.list && this.list.length > 0) {
					this.list.forEach(item => {
						Object.assign(item, {
							checked: false
						});
					});
				}

				console.log('this.list', this.list);
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 查询用户可抵扣积分
		async queryIntegrals() {
			const result = await this.$http.get({
				url: this.$api.querySelectIntegral,
				data: {
					siteId: uni.getStorageSync('siteId'), // 站点id
					userId: uni.getStorageSync('userId'), //登录用户的id
					packId: this.projectInfo.id //套餐商品id
				}
			});
			if (result.code == 200) {
				console.log('查询用户可抵扣积分result', result);
				this.pointsUsed = result.data.usingPoints; //可抵扣积分
				this.deductionAmount = result.data.integer; //可抵扣金额
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 查询预估车费
		async getFare() {
			const result = await this.$http.get({
				url: this.$api.getSelectEstimatedFare,
				data: {
					siteId: uni.getStorageSync('siteId'), // 站点id
					technicianId: this.technicianInfo.id, //理疗师id
					/* accuracy: 111.59244,
					latitude: 26.46098 */
					accuracy: this.addressItem.longitude, //经度（小数点类型）
					latitude: this.addressItem.latitude //纬度（小数点类型）
				}
			});
			if (result.code == 200) {
				console.log('查询预估车费result', result);
				// getResult经纬度距离  startingKilometre起步价  exceedExpense超出每公里费用  fare车费
				this.fareInfo = result.data;
				let getResult = this.fareInfo.getResult || 0;
				let startingKilometre = this.fareInfo.startingKilometre || 0;
				let exceedExpense = this.fareInfo.exceedExpense || 0;
				this.details =
					'直线距离' +
					getResult +
					'km，不是导航距离!每个订单都需要付给理疗师往返路费，打车费由高德地图估算。起步' +
					startingKilometre +
					'元。超出每公里增加' +
					exceedExpense +
					'元';
				console.log('查询预估车费this.details', this.details);
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 更新优惠卷状态【查询领卷大厅，我的卡券前，需调用该接口】
		async updateDiscountCoupons(id) {
			const result = await this.$http.get({
				url: this.$api.updateDiscountCouponType
			});
			if (result.code == 200) {
				console.log('更新优惠卷状态result', result);
				this.mescroll.resetUpScroll();
			} else {
				this.$sun.toast(result.message);
			}
		},

		// 我的卡券列表
		/* async upCallback(scroll) {
				const result = await this.$http.get({
					url: this.$api.myCardPage,
					data: {
						page: scroll.num,
						limit: 10,
						siteId: uni.getStorageSync('siteId'), // 站点id
						userId: uni.getStorageSync('userId'), //登录用户的id
						discountCouponStatus: '' //筛选——优惠券状态(1.已使用 2.未使用 3.已过期)
					}
				});
				if (result.code == 200) {
					console.log('我的卡券列表', result);
					this.mescroll.endByPage(result.data.list.length, this.$sun.pagingSum(result.data.count, 10));
					if (scroll.num == 1) this.list = [];
					this.list = this.list.concat(result.data.list);
					console.log('this.list', this.list, this.list.length);
				}
			}, */
		// 备注
		descInput(e) {
			this.remnant = e.detail.value.length;
			if (this.remnant >= 50) {
				this.$sun.toast('订单备注已达上限');
			}
		},
		// 选择地址
		selectAddress() {
			this.$sun.navGo('/pages/user/my/address-management/address-management');
		},
		// 提交订单
		confirm() {
			if (!this.addressItem || !this.addressItem.id) {
				this.$sun.toast('请选择地址');
				return;
			} else if (!this.serviceStartTime) {
				this.$sun.toast('请选择服务时间');
				return;
			}
			if (!this.agreeChecked) {
				this.$sun.toast('请先阅读并同意《平台交易规则》');
				this.animation = 'shake';
				setTimeout(() => {
					this.animation = '';
				}, 1300);
				return;
			} else {
				/* if (!this.agreeChecked) {
					this.agreeOpen();
				} */
				this.agreeClick();
			}
		},
		agreeClick() {
			// this.agreeClose();
			// 支付方式：1 余额支付  2 微信支付
			if (this.applyType == 1) {
				uni.showModal({
					// title: '提示',
					confirmColor: '#FF0202',
					content: '确定使用余额支付吗?',
					success: async res => {
						// 确定
						if (res.confirm) {
							this.$at.uniDoFunc({
								// 键名
								key: 'submit',
								success: async () => {
									//锁定
									this.$at.lockKey('submit');
									this.save();
								}
							});
						}
						// 取消
						else {
							this.$sun.toast('取消了支付');
						}
					}
				});
			} else {
				this.$at.uniDoFunc({
					// 键名
					key: 'submit',
					success: async () => {
						//锁定
						this.$at.lockKey('submit');
						this.save();
					}
				});
			}
		},
		async save() {
			this.isSuccess = false;
			let serviceStartTime = this.serviceStartTime + ':00';
			// let serviceStartTime = new Date(serviceStartTime).getTime(); // 日期传13位时间戳
			console.log('serviceStartTime', serviceStartTime);
			let pointsUsed = this.checked == true ? this.pointsUsed : 0;
			const result = await this.$http.post({
				url: this.$api.createUpdate,
				data: {
					siteId: uni.getStorageSync('siteId'), // 站点id
					userId: uni.getStorageSync('userId'), //登录用户的id
					// technicianEvaluationId: this.technicianInfo.id, //理疗师id
					// packageListId: this.projectInfo.id, //商品id
					// number: 1, //数量
					serviceTime: this.projectInfo.serviceTime, //服务时间/分钟
					// serviceStartTime: serviceStartTime, //服务开始时间
					// fatherOrderNumber: '', //加钟交类订单编号
					// plusClockPrice: '', //加钟价格
					// fareDetails: this.orderNotes, //车费详情
					// remark: this.orderNotes, //订单详情
					// expensesIncurred: this.fareInfo.fare ? this.fareInfo.fare : 0, //出行费用
					// pointsUsed: pointsUsed, //所用积分
					// cardRollId: this.couponDeduction.id || '', //卡券id
					// deductionAmount: this.allDeductionMoney, //抵扣金额
					// disbursements: Number(this.sum), //实付款
					// addressManagementId: this.addressItem.id, //地址id
					// addressManagements:
					// 	this.addressItem.province +
					// 	' ' +
					// 	this.addressItem.city +
					// 	' ' +
					// 	this.addressItem.district +
					// 	' ' +
					// 	this.addressItem.address +
					// 	' ' +
					// 	this.addressItem.detailsAddress,
					// reasonForRejection: '', //驳回原因
					// status: this.applyType == 1 ? 1 : 0, //订单状态 (0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款）
					// payMethod: this.applyType, //支付方式 1：余额 2：微信
					// payStatus: this.applyType == 1 ? 1 : 2 //支付状态 1：已支付 2：未支付

					// /* status: 0, //订单状态 (0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款）
					// payMethod: 2, //支付方式 1：余额 2：微信
					// payStatus: 2 //支付状态 1：已支付 2：未支付 */
				}
			});
			if (result.code == 200) {
				console.log('提交订单result', result, 'this.applyType', this.applyType, 'result.data', result.data);
				// 余额支付
				if (this.applyType == 1) {
					// 普通商品_我的订单页
					this.$sun.navRe('/pages/user/order/order', { id: 1 });
				} else {
					const pay = result.data;
					await this.$wx.config({
						debug: false,
						appId: pay.appId,
						timestamp: pay.timeStamp,
						nonceStr: pay.nonceStr,
						paySign: pay.paySign,
						jsApiList: ['chooseWXPay']
					});
					await this.$wx.chooseWXPay({
						timestamp: pay.timeStamp,
						nonceStr: pay.nonceStr,
						package: pay.package,
						signType: pay.signType,
						paySign: pay.paySign,
						appId: pay.appId,
						out_trade_no: pay.out_trade_no,
						success: async res => {
							this.isSuccess = true;
							this.$sun.toast('进入支付成功111');
							console.log('进入支付成功2222222', res);
							this.$sun.navRe('/pages/user/order/order', {
								id: 1
							});
							// 后台修改状态，则不需要重复调用接口
							// this.wxOrder();
						},
						fail: async err => {
							this.$sun.toast('取消了支付');
							this.$at.releaseKey('submit');
							this.$sun.navRe('/pages/user/order/order', {
								id: 1
							});
						},
						complete: async res => {
							if (this.isSuccess == true) {
								console.log('进入支付成功回调===========', res);

								// this.$sun.toast('进入支付成功回调'+res);
							} else {
								this.$sun.toast('取消了支付');
								this.$at.releaseKey('submit');
								this.$sun.navRe('/pages/user/order/order', {
									id: 1
								});
							}
							console.log('进入测试回调===========', res);
						}
					});
				}
			} else {
				this.$sun.toast('进入支付失败222');
				this.$at.releaseKey('submit');
				this.$sun.toast(result.message);
			}
		},

		// 微信支付再次调用，更改订单状态
		async wxOrder() {
			let serviceStartTime = this.serviceStartTime + ':00';
			console.log('serviceStartTime', serviceStartTime);
			let pointsUsed = this.checked == true ? this.pointsUsed : 0;
			const result = await this.$http.post({
				url: this.$api.orderSave,
				data: {
					siteId: uni.getStorageSync('siteId'), // 站点id
					userId: uni.getStorageSync('userId'), //登录用户的id
					technicianEvaluationId: this.technicianInfo.id, //理疗师id
					packageListId: this.projectInfo.id, //商品id
					number: 1, //数量
					serviceTime: this.projectInfo.serviceTime, //服务时间/分钟
					serviceStartTime: serviceStartTime, //服务开始时间
					fatherOrderNumber: '', //加钟交类订单编号
					plusClockPrice: '', //加钟价格
					// fareDetails: this.orderNotes, //车费详情
					remark: this.orderNotes, //订单详情
					expensesIncurred: this.fareInfo.fare ? this.fareInfo.fare : 0, //出行费用
					pointsUsed: pointsUsed, //所用积分
					cardRollId: this.couponDeduction.id || '', //卡券id
					deductionAmount: this.allDeductionMoney, //抵扣金额
					disbursements: Number(this.sum), //实付款
					addressManagementId: this.addressItem.id, //地址id
					reasonForRejection: '', //驳回原因
					status: 1, //订单状态 (0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款）
					payMethod: 2, //支付方式 1：余额 2：微信
					payStatus: 1 //支付状态 1：已支付 2：未支付
				}
			});
			if (result.code == 200) {
				console.log('微信支付再次调用，更改订单状态result', result);
				this.$sun.navRe('/pages/user/order/order', {
					id: 2
				});
			} else {
				this.$at.releaseKey('submit');
				this.$sun.toast(result.message);
			}
		}
	}
};
</script>

<style lang="less">
/deep/ .radio-disabled .uni-radio-input {
	background-color: #c9c9c9 !important;
}
/deep/ .uni-textarea-textarea {
	max-width: 620rpx;
	font-size: 28rpx;
	line-height: 45rpx;
}
page {
	background-color: #f7f7f7;
}

.confirm-order-page {
	padding-bottom: 160rpx;

	.p-align40 {
		padding-top: 40rpx !important;
		padding-bottom: 40rpx !important;
	}

	.card-cls {
		width: 650rpx;
		padding: 30rpx 20rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
		background: #fff;

		// 备注
		.p-notes {
			padding: 14rpx 0rpx;

			// 多行文本
			.textarea-box {
				border-radius: 20rpx;
				padding: 20rpx;
				background: #f6f6f6;
				margin-top: 26rpx;

				.textarea-color {
					color: #999;
				}
			}

			.refund-price {
				color: #f00;
				font-size: 24rpx;

				text {
					font-size: 32rpx;
					font-weight: bold;
				}
			}
		}

		.zfimg-cls {
			width: 48rpx;
			height: 48rpx;
			margin: 0 24rpx 0 10rpx;
		}
	}

	.address-all {
		.icon-bj {
			width: 68rpx;
			height: 68rpx;
			background-image: linear-gradient(92deg, #26c278 1.2%, #28c263 94.92%);
			border-radius: 50%;

			text {
				z-index: 99;
				color: #fff;
				font-size: 42rpx;
			}
		}

		.address-content {
			flex: 1;
			font-size: 32rpx;
			margin: 0 26rpx;
		}

		image {
			height: 32rpx;
			width: 32rpx;
		}
	}

	// 项目图片
	.project-img {
		width: 162rpx;
		height: 162rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}

	.height81 {
		height: 180rpx;
		// height: 162rpx;
	}

	// 支付订单
	.confirm-bottom {
		z-index: 999;
		background-color: #fff;
		width: calc(100% - 20px);
		position: fixed;
		bottom: 0rpx;
		border-top: 2rpx solid #dfdfdf;
		padding: 26rpx 20rpx;

		.sum-price {
			margin-bottom: 12rpx;
			margin-right: 20rpx;

			text {
				color: #f00;
				font-size: 36rpx;
			}
		}

		button {
			margin: 0rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 28rpx;
			width: 180rpx;
			height: 76rpx;
			border-radius: 76rpx;
			background: #19c866;
		}
	}

	.coupon-cls {
		font-size: 24rpx;
		font-weight: 500;
		border-radius: 6px;
		background: #eb6941;
		padding: 4rpx 10rpx;
		display: inline-block;
	}

	// '优惠券'弹框样式
	.v-coupon-pop {
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		padding: 30rpx 0 20rpx;
		background-color: #fff;
		z-index: 999;

		.coupon-card {
			position: relative;
			margin: 20rpx;
			padding: 20rpx;
			border-radius: 10px;
			background: #fef9f6;

			.identifying {
				position: absolute;
				top: -10rpx;
				color: #fff;
			}

			.coupon-price {
				margin-right: 40rpx;
				color: #ff753c;

				text {
					padding-right: 8rpx;
					font-size: 48rpx;
					font-weight: bold;
				}
			}

			.v-time {
				margin: 16rpx 0;
				color: #bfbfbf;
				font-size: 24rpx;
				font-weight: 500;
			}

			.v-discount {
				background: #fcede7;
				color: #ec6d42;
				font-size: 24rpx;
				font-weight: 500;
				padding: 4rpx 10rpx;
				display: inline-block;
			}

			.receive-cls {
				color: #fff;
				font-size: 24rpx;
				width: 104rpx;
				height: 40rpx;
				border-radius: 8rpx;
				background: #f28331;
			}

			.coupon-hint {
				border-top: 2rpx dashed #bfbfbf;
				padding: 22rpx 4rpx;
				color: #666;
				font-size: 24rpx;
				font-weight: 500;
			}
		}
	}

	// '服务时间'弹框样式
	.v-time-pop {
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		padding: 30rpx 0 20rpx;
		background-color: #fff;
		z-index: 999;

		.time-cls,
		.sel-time-cls,
		.none-time-cls {
			border-radius: 20rpx;
			margin-left: 20rpx;
			margin-bottom: 20rpx;
			width: calc(100% / 4 - 26px);
			padding: 20rpx 10rpx;
			color: #666;
		}

		.time-cls {
			border: 2rpx solid #e5e5e5;
			color: #666;
		}

		.sel-time-cls {
			border: 2rpx solid #25c376;
			background: #25c376;
			color: #f9fffe;
		}

		.none-time-cls {
			background: #e5e5e5;
			color: #c9c9c9;
		}
	}

	// 隐私协议 样式
	.v-agree-pop {
		width: 500rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 60rpx 50rpx;
		.v-title {
			font-size: 40rpx;
			font-weight: bold;
		}
		.agree-name {
			padding: 30rpx 0;
			color: #19c866;
			font-size: 30rpx;
			font-weight: bold;
		}
		.agree-confirm {
			margin: 20rpx 40rpx 0;
			height: 80rpx;
			color: #fff;
			border-radius: 20rpx;
			background: linear-gradient(90deg, #0ac364 0%, #14df79 100%);
		}
		.agree-cancle {
			margin: 20rpx 40rpx 0;
			height: 80rpx;
			color: #666;
		}
	}

	/* 隐私协议 start */
	.radioText {
		margin: 38rpx 0;
	}
	.agree {
		color: #666;
		text {
			// color: #1890ff;
			color: #19c866;
		}
	}

	.animation {
		width: 10rem;
		height: 2rem;
		background: #ffffff;
		margin-top: 0.5rem;
	}
	.animation-shake {
		animation: shake 0.3s !important;
	}
	@keyframes shake {
		0%,
		100% {
			transform: translateX(0);
		}

		10% {
			transform: translateX(-9px);
		}

		20% {
			transform: translateX(8px);
		}

		30% {
			transform: translateX(-7px);
		}

		40% {
			transform: translateX(6px);
		}

		50% {
			transform: translateX(-5px);
		}

		60% {
			transform: translateX(4px);
		}

		70% {
			transform: translateX(-3px);
		}

		80% {
			transform: translateX(2px);
		}

		90% {
			transform: translateX(-1px);
		}
	}
	/* 隐私协议 end */

	.confirm-time {
		height: 90rpx;
		margin: 20rpx 80rpx;
		color: #fff;
		border-radius: 56rpx;
		background: linear-gradient(90deg, #0ac364 0%, #14df79 100%);
	}
}
</style>
